﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using D3DSS.DataContract;
using D3DSS.Http;
using D3DSS.FormUI.Properties;
using System.Net;

namespace D3DSS.FormUI
{
    public partial class frmUpdate : Form
    {
        protected string downloadUrl { get; set; }
        protected string Version { get; set; }

        public frmUpdate()
        {
            InitializeComponent();
        }

        private void frmUpdate_Load(object sender, EventArgs e)
        {
            this.Hide();
            var request = new UpdateRequest();
            request.Version = ProductVersion;
            this.Version = request.Version;
            var response = HttpRequest.Post<Response<UpdateResponse>>(Settings.Default.UpdateUrl, request);
            if (response.Item1.IsSuccess)
            {
                if (response.Item1.Data.IsUpdate)
                {
                    this.Show();
                    this.Activate();
                    this.WindowState = FormWindowState.Normal;
                    rtbUpdate.Text = response.Item1.Data.UpdateNote;
                    downloadUrl = response.Item1.Data.DownloadUrl;
                }
                else
                {
                    this.DialogResult = DialogResult.OK;
                }
            }
            else
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            WebClient client = new WebClient();
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadFileAsync(new Uri(downloadUrl), AppDomain.CurrentDomain.BaseDirectory + @"\D3DSS_" + this.Version + ".zip");
            
        }

        private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            pbUpdate.Value = e.ProgressPercentage;
        }

        private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show(AppDomain.CurrentDomain.BaseDirectory + @"\D3DSS_" + Version + ".zip 下载完成！");
            this.Close();
        }
    }
}
